<template>
  <div class="teacher-schedule">
    <div class="page-header">
      <h2>我的课表</h2>
    </div>

    <!-- 筛选条件 -->
    <el-card class="filter-card" shadow="never">
      <el-form :model="filterForm" :inline="true" class="filter-form">
        <el-form-item label="学期">
          <el-select
            v-model="filterForm.semester"
            placeholder="请选择学期"
            clearable
            style="width: 200px"
            @change="handleFilter"
          >
            <el-option label="2024春季" value="2024春季" />
            <el-option label="2024秋季" value="2024秋季" />
            <el-option label="2025春季" value="2025春季" />
            <el-option label="2025秋季" value="2025秋季" />
          </el-select>
        </el-form-item>
        
        
        <el-form-item label="周次">
          <el-select
            v-model="filterForm.week"
            placeholder="请选择周次"
            clearable
            style="width: 150px"
            @change="handleFilter"
          >
            <el-option
              v-for="week in 20"
              :key="week"
              :label="`第${week}周`"
              :value="week"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleFilter">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 课表展示 -->
    <el-card class="schedule-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>课程安排</span>
          <div class="header-actions">
            <el-button type="success" @click="exportSchedule">
              <el-icon><Download /></el-icon>
              导出课表
            </el-button>
          </div>
        </div>
      </template>
      
      <div class="schedule-content">
        <!-- 周视图 -->
        <div v-if="viewMode === 'week'" class="week-view">
          <div class="week-header">
            <div class="time-slot">时间</div>
            <div
              v-for="day in weekDays"
              :key="day.value"
              class="day-header"
            >
              {{ day.label }}
            </div>
          </div>
          
          <div class="week-body">
            <div
              v-for="timeSlot in timeSlots"
              :key="timeSlot.value"
              class="time-row"
            >
              <div class="time-label">{{ timeSlot.label }}</div>
              <div
                v-for="day in weekDays"
                :key="day.value"
                class="day-cell"
              >
                <div
                  v-for="course in getCourseByTimeAndDay(timeSlot.value, day.value)"
                  :key="course.scheduleId"
                  class="course-item"
                  :class="course.status"
                  @click="handleViewDetail(course)"
                >
                  <div class="course-name">{{ course.courseName }}</div>
                  <div class="course-info">
                    <span>{{ course.clazzName }}</span>
                    <span>{{ course.classroomName }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 列表视图 -->
        <div v-else class="list-view">
          <el-table
            :data="scheduleList"
            v-loading="loading"
            stripe
            border
            style="width: 100%"
          >
            <el-table-column prop="courseName" label="课程名称" width="150" />
            <el-table-column prop="clazzName" label="班级" width="120" />
            <el-table-column prop="weekDay" label="星期" width="80">
              <template #default="scope">
                {{ getWeekDayName(scope.row.weekDay) }}
              </template>
            </el-table-column>
            <el-table-column prop="timeSlot" label="节次" width="100">
              <template #default="scope">
                第{{ scope.row.timeSlot }}节
              </template>
            </el-table-column>
            <el-table-column prop="classroomName" label="教室" width="120" />
            <el-table-column prop="semester" label="学期" width="120" />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="scope">
                <el-tag :type="getStatusType(scope.row.status)">
                  {{ getStatusText(scope.row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150">
              <template #default="scope">
                <el-button
                  type="primary"
                  size="small"
                  @click="handleViewDetail(scope.row)"
                >
                  查看详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-card>

    <!-- 课程详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="课程详情"
      width="600px"
    >
      <div class="course-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="课程名称">
            {{ courseDetail.courseName }}
          </el-descriptions-item>
          <el-descriptions-item label="班级">
            {{ courseDetail.clazzName }}
          </el-descriptions-item>
          <el-descriptions-item label="星期">
            {{ getWeekDayName(courseDetail.weekDay) }}
          </el-descriptions-item>
          <el-descriptions-item label="节次">
            第{{ courseDetail.timeSlot }}节
          </el-descriptions-item>
          <el-descriptions-item label="教室">
            {{ courseDetail.classroomName }}
          </el-descriptions-item>
          <el-descriptions-item label="学期">
            {{ courseDetail.semester }}
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(courseDetail.status)">
              {{ getStatusText(courseDetail.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="备注">
            {{ courseDetail.remark || '无' }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, Refresh, Download } from '@element-plus/icons-vue'
import { getTeacherSchedule, getTeacherWeekSchedule, getTeacherTodaySchedule } from '../api/teacherUser'

// 筛选表单
const filterForm = reactive({
  semester: '2024春季',
  week: ''
})

// 视图模式
const viewMode = ref('week') // 'week' | 'list'

// 加载状态
const loading = ref(false)

// 课表数据
const scheduleList = ref([])

// 详情对话框
const detailDialogVisible = ref(false)
const courseDetail = ref({})

// 星期数据
const weekDays = [
  { label: '星期一', value: 1 },
  { label: '星期二', value: 2 },
  { label: '星期三', value: 3 },
  { label: '星期四', value: 4 },
  { label: '星期五', value: 5 },
  { label: '星期六', value: 6 },
  { label: '星期日', value: 7 }
]

// 时间段数据（每天4节）
const timeSlots = [
  { label: '08:30-09:50', value: 1 },
  { label: '10:05-11:25', value: 2 },
  { label: '12:55-14:25', value: 3 },
  { label: '14:40-16:10', value: 4 }
]

// 获取星期名称
const getWeekDayName = (day) => {
  const dayMap = {
    1: '星期一', 2: '星期二', 3: '星期三', 4: '星期四',
    5: '星期五', 6: '星期六', 7: '星期日'
  }
  return dayMap[day] || ''
}

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    'normal': 'success',
    'cancelled': 'danger',
    'postponed': 'warning',
    'completed': 'info'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    'normal': '正常',
    'cancelled': '已取消',
    'postponed': '已延期',
    'completed': '已完成'
  }
  return statusMap[status] || '未知'
}

// 根据时间和星期获取课程
const getCourseByTimeAndDay = (periodNo, dayOfWeek) => {
  return scheduleList.value.filter(course => 
    (course.periodNo === periodNo || course.timeSlot === periodNo) &&
    (course.dayOfWeek === dayOfWeek || course.weekDay === dayOfWeek)
  )
}

// 获取课表数据
const fetchSchedule = async () => {
  loading.value = true
  
  try {
    const user = JSON.parse(localStorage.getItem('user') || '{}')
    const teacherId = user.teacherId || user.teacher_id || user.id
    if (!teacherId) {
      ElMessage.error('请先登录')
      return
    }

    let response
    if (filterForm.week) {
      // 获取本周课表
      response = await getTeacherWeekSchedule(teacherId, filterForm.semester || 'advanced', filterForm.week)
    } else {
      // 获取整个学期课表
      response = await getTeacherSchedule(teacherId, filterForm.semester || 'advanced')
    }
    
    if (response && response.data) {
      scheduleList.value = response.data
      // 若本学期无数据，自动回退到 2025春季 再试一次
      if ((!Array.isArray(response.data) || response.data.length === 0) && (filterForm.semester || '2024春季') !== '2025春季') {
        const fallbackSemester = '2025春季'
        const resp2 = await getTeacherSchedule(teacherId, fallbackSemester)
        if (resp2 && Array.isArray(resp2.data) && resp2.data.length > 0) {
          filterForm.semester = fallbackSemester
          scheduleList.value = resp2.data
        }
      }
    } else {
      scheduleList.value = []
    }
    
  } catch (error) {
    console.error('获取课表失败:', error)
    // 显示模拟数据作为备选
    const mockData = [
      {
        scheduleId: 1,
        courseName: '高等数学',
        clazzName: '计算机1班',
        weekDay: 1,
        timeSlot: 1,
        classroomName: 'A101',
        semester: '2024春季',
        status: 'normal',
        remark: '正常上课'
      },
      {
        scheduleId: 2,
        courseName: '线性代数',
        clazzName: '计算机2班',
        weekDay: 2,
        timeSlot: 3,
        classroomName: 'A102',
        semester: '2024春季',
        status: 'normal',
        remark: '正常上课'
      },
      {
        scheduleId: 3,
        courseName: '数据结构',
        clazzName: '计算机1班',
        weekDay: 3,
        timeSlot: 5,
        classroomName: 'B201',
        semester: '2024春季',
        status: 'normal',
        remark: '正常上课'
      }
    ]
    scheduleList.value = mockData
  } finally {
    loading.value = false
  }
}

// 筛选
const handleFilter = () => {
  fetchSchedule()
}

// 重置筛选
const handleReset = () => {
  filterForm.semester = '2024春季'
  filterForm.week = ''
  fetchSchedule()
}

// 查看详情
const handleViewDetail = (row) => {
  courseDetail.value = { ...row }
  detailDialogVisible.value = true
}

// 导出课表
const exportSchedule = () => {
  if (!scheduleList.value || scheduleList.value.length === 0) {
    ElMessage.warning('暂无课表数据可导出')
    return
  }

  try {
    // 获取用户信息
    const user = JSON.parse(localStorage.getItem('user') || '{}')
    const teacherName = user.teName || user.teacherName || '教师'
    const semester = filterForm.semester || '全部学期'
    const week = filterForm.week ? `第${filterForm.week}周` : '全学期'
    
    // 创建CSV内容
    let csvContent = '\uFEFF' // BOM for UTF-8
    
    // 标题信息
    csvContent += `教师课表\n`
    csvContent += `教师姓名：${teacherName}\n`
    csvContent += `学期：${semester}\n`
    csvContent += `周次：${week}\n`
    csvContent += `导出时间：${new Date().toLocaleString('zh-CN')}\n\n`
    
    // 表头
    csvContent += `序号,课程名称,班级,星期,时间段,教室,状态,备注\n`
    
    // 数据行
    scheduleList.value.forEach((course, index) => {
      const weekDay = getWeekDayName(course.dayOfWeek || course.weekDay)
      const timeSlot = getTimeSlotLabel(course.periodNo || course.timeSlot)
      const status = getStatusText(course.status)
      const remark = (course.remark || course.scheduleRemark || '').replace(/,/g, '，') // 替换逗号避免CSV格式问题
      
      csvContent += `${index + 1},${course.courseName},${course.clazzName},${weekDay},${timeSlot},${course.classroomName},${status},${remark}\n`
    })
    
    // 统计信息
    csvContent += `\n统计信息\n`
    csvContent += `总课程数,${scheduleList.value.length}\n`
    
    // 按星期统计
    const weekStats = {}
    scheduleList.value.forEach(course => {
      const day = course.dayOfWeek || course.weekDay
      weekStats[day] = (weekStats[day] || 0) + 1
    })
    
    csvContent += `\n按星期统计\n`
    weekDays.forEach(day => {
      csvContent += `${day.label},${weekStats[day.value] || 0}节\n`
    })
    
    // 创建Blob并下载
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
    const link = document.createElement('a')
    const url = URL.createObjectURL(blob)
    
    const fileName = `教师课表_${teacherName}_${semester}_${week}_${new Date().getTime()}.csv`
    link.setAttribute('href', url)
    link.setAttribute('download', fileName)
    link.style.visibility = 'hidden'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    
    ElMessage.success(`课表导出成功！共 ${scheduleList.value.length} 节课`)
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败: ' + error.message)
  }
}

// 获取时间段标签
const getTimeSlotLabel = (slot) => {
  const timeSlot = timeSlots.find(t => t.value === slot)
  return timeSlot ? timeSlot.label : `第${slot}节`
}

// 组件挂载时获取数据
onMounted(() => {
  fetchSchedule()
})
</script>

<style scoped>
.teacher-schedule {
  background: #f5f7fa;
  padding: 20px;
  font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
  box-sizing: border-box;
}

.page-header {
  margin-bottom: 32px;
  text-align: center;
}

.page-header h2 {
  margin: 0;
  color: #2c3e50;
  font-size: 28px;
  font-weight: 600;
  letter-spacing: 1px;
}

.filter-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border: 1px solid #e4e7ed;
  background: #ffffff;
}

.filter-card :deep(.el-card__body) {
  padding: 20px;
}

.filter-form {
  margin-bottom: 0;
}

.filter-form :deep(.el-form-item) {
  margin-bottom: 16px;
  margin-right: 24px;
}

.filter-form :deep(.el-form-item__label) {
  font-weight: 600;
  color: #2c3e50;
  font-size: 14px;
}

.schedule-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border: 1px solid #e4e7ed;
  background: #ffffff;
  overflow: hidden;
}

.schedule-card :deep(.el-card__header) {
  background: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
  padding: 16px 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header span {
  color: #2c3e50;
  font-weight: 600;
  font-size: 16px;
}

.header-actions .el-button {
  border-radius: 4px;
  font-weight: 500;
  padding: 8px 16px;
  transition: all 0.3s ease;
}

.schedule-content {
  padding: 20px;
}

/* 周视图样式 */
.week-view {
  border: 1px solid #dcdfe6;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.week-header {
  display: grid;
  grid-template-columns: 120px repeat(7, 1fr);
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-bottom: 2px solid #5a67d8;
}

.time-slot, .day-header {
  padding: 16px 12px;
  text-align: center;
  font-weight: 600;
  color: #ffffff;
  border-right: 1px solid rgba(255, 255, 255, 0.2);
  font-size: 14px;
}

.day-header:last-child {
  border-right: none;
}

.week-body {
  background: #ffffff;
}

.time-row {
  display: grid;
  grid-template-columns: 120px repeat(7, 1fr);
  border-bottom: 1px solid #e4e7ed;
  min-height: 90px;
}

.time-row:last-child {
  border-bottom: none;
}

.time-label {
  padding: 16px 12px;
  text-align: center;
  font-size: 13px;
  font-weight: 500;
  color: #606266;
  background: #f8f9fa;
  border-right: 1px solid #e4e7ed;
  display: flex;
  align-items: center;
  justify-content: center;
}

.day-cell {
  padding: 8px;
  border-right: 1px solid #e4e7ed;
  min-height: 90px;
  position: relative;
  background: #fafbfc;
  transition: background 0.2s ease;
}

.day-cell:hover {
  background: #f5f7fa;
}

.day-cell:last-child {
  border-right: none;
}

.course-item {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #ffffff;
  padding: 10px 12px;
  border-radius: 8px;
  font-size: 13px;
  margin-bottom: 6px;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  box-shadow: 0 2px 6px rgba(102, 126, 234, 0.3);
  border-left: 3px solid rgba(255, 255, 255, 0.5);
}

.course-item:hover {
  transform: translateY(-2px) scale(1.02);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.5);
  background: linear-gradient(135deg, #7c8ff0 0%, #8a5db8 100%);
}

.course-item.cancelled {
  background: linear-gradient(135deg, #f56c6c 0%, #e74c3c 100%);
  box-shadow: 0 2px 6px rgba(245, 108, 108, 0.3);
  border-left-color: rgba(255, 255, 255, 0.5);
}

.course-item.cancelled:hover {
  box-shadow: 0 4px 12px rgba(245, 108, 108, 0.5);
}

.course-item.postponed {
  background: linear-gradient(135deg, #f39c12 0%, #e67e22 100%);
  box-shadow: 0 2px 6px rgba(230, 162, 60, 0.3);
  border-left-color: rgba(255, 255, 255, 0.5);
}

.course-item.postponed:hover {
  box-shadow: 0 4px 12px rgba(230, 162, 60, 0.5);
}

.course-item.completed {
  background: linear-gradient(135deg, #95a5a6 0%, #7f8c8d 100%);
  box-shadow: 0 2px 6px rgba(144, 147, 153, 0.3);
  border-left-color: rgba(255, 255, 255, 0.5);
}

.course-item.completed:hover {
  box-shadow: 0 4px 12px rgba(144, 147, 153, 0.5);
}

.course-name {
  font-weight: 700;
  margin-bottom: 6px;
  font-size: 14px;
  line-height: 1.3;
}

.course-info {
  font-size: 11px;
  opacity: 0.95;
  line-height: 1.5;
}

.course-info span {
  display: block;
  margin-bottom: 2px;
}

.course-info span:last-child {
  margin-bottom: 0;
}

/* 列表视图样式 */
.list-view :deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

.list-view :deep(.el-table__header) {
  background: #f5f7fa;
}

.list-view :deep(.el-table th) {
  background: transparent;
  color: #2c3e50;
  font-weight: 600;
  font-size: 14px;
  border-bottom: 1px solid #ebeef5;
  padding: 12px;
}

.list-view :deep(.el-table td) {
  padding: 12px;
  border-bottom: 1px solid #ebeef5;
  color: #606266;
  font-size: 14px;
}

.list-view :deep(.el-table__row:hover) {
  background: #f5f7fa;
}

.list-view :deep(.el-table__row:nth-child(even)) {
  background: #fafafa;
}

.list-view :deep(.el-table__row:nth-child(even):hover) {
  background: #f5f7fa;
}

.list-view :deep(.el-button) {
  border-radius: 4px;
  font-weight: 500;
  padding: 6px 12px;
  font-size: 12px;
  transition: all 0.3s ease;
}

/* 课程详情样式 */
.course-detail {
  padding: 20px 0;
}

.course-detail :deep(.el-descriptions) {
  border-radius: 8px;
  overflow: hidden;
}

.course-detail :deep(.el-descriptions__header) {
  background: #f5f7fa;
  padding: 16px 20px;
  border-bottom: 1px solid #ebeef5;
}

.course-detail :deep(.el-descriptions__title) {
  color: #2c3e50;
  font-weight: 600;
  font-size: 16px;
}

.course-detail :deep(.el-descriptions__body) {
  background: #ffffff;
}

.course-detail :deep(.el-descriptions-item__label) {
  background: #fafafa;
  color: #606266;
  font-weight: 600;
  width: 120px;
}

.course-detail :deep(.el-descriptions-item__content) {
  color: #2c3e50;
  padding: 12px 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding-top: 16px;
}

.dialog-footer .el-button {
  border-radius: 4px;
  font-weight: 500;
  padding: 10px 20px;
  transition: all 0.3s ease;
}

/* 对话框样式优化 */
:deep(.el-dialog) {
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  border: 1px solid #e4e7ed;
}

:deep(.el-dialog__header) {
  background: #f5f7fa;
  border-radius: 8px 8px 0 0;
  padding: 16px 20px;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-dialog__title) {
  color: #2c3e50;
  font-weight: 600;
  font-size: 16px;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-dialog__footer) {
  padding: 16px 20px;
  background: #f5f7fa;
  border-radius: 0 0 8px 8px;
  border-top: 1px solid #ebeef5;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .teacher-schedule {
    padding: 16px;
  }
  
  .page-header h2 {
    font-size: 24px;
  }
  
  .filter-form :deep(.el-form-item) {
    margin-right: 0;
    width: 100%;
  }
  
  .filter-form :deep(.el-input),
  .filter-form :deep(.el-select) {
    width: 100%;
  }
  
  .week-header,
  .time-row {
    grid-template-columns: 90px repeat(7, 1fr);
  }
  
  .time-slot,
  .time-label {
    font-size: 11px;
    padding: 10px 6px;
  }
  
  .day-header,
  .day-cell {
    padding: 10px 6px;
  }
  
  .course-item {
    font-size: 11px;
    padding: 6px 8px;
  }
  
  .course-name {
    font-size: 12px;
  }
  
  .course-info {
    font-size: 10px;
  }
}

@media (max-width: 480px) {
  .teacher-schedule {
    padding: 12px;
  }
  
  .page-header h2 {
    font-size: 20px;
  }
  
  .filter-card :deep(.el-card__body) {
    padding: 16px;
  }
  
  .schedule-content {
    padding: 16px;
  }
  
  .week-header,
  .time-row {
    grid-template-columns: 70px repeat(7, 1fr);
  }
  
  .time-slot,
  .time-label {
    font-size: 10px;
    padding: 8px 4px;
  }
  
  .day-header,
  .day-cell {
    padding: 8px 4px;
  }
  
  .course-item {
    font-size: 10px;
    padding: 4px 6px;
  }
  
  .course-name {
    font-size: 11px;
  }
  
  .course-info {
    font-size: 9px;
  }
}
</style>


